import {
  BarsOutlined,
  CarOutlined,
  CheckCircleOutlined,
  ContainerOutlined,
  FieldTimeOutlined,
  LoadingOutlined,
  PayCircleOutlined,
  PictureOutlined,
  ReconciliationOutlined,
  SmileOutlined,
} from '@ant-design/icons';
import { ProCard } from '@ant-design/pro-components';
import { useHistory, useModel } from 'umi';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Image, message, Steps, Tooltip } from 'antd';
import { useState, useEffect } from 'react';
import { getParkingOrder } from '../service';
import type { ParkingOrderDetail } from '../types.d';
import styles from './style.less';
import EnhancedTag from './components/EnhancedTag';
import { diffTimes, handleInOutType, numFormat, timeRender } from '@/utils/utils';
import EnhancedTip from './components/EnhancedTip';
import ChargeRule from './components/ChargeRule';
import LoadInfo from '@/components/LoadInfo';
import ChangePlate from './components/ChangePlate';
import ChangeTime from './components/ChangeTime';
import ChangeLogList from './components/ChangeLogList';
import ChangeTimeList from './components/ChangeTimeList';
import PaymentRecord from './components/PaymentRecord';
import CancelOrder from '../components/CancelOrder';
import { Auths } from '@/utils/types.d';

type TStatus = 'error' | 'process' | 'finish' | 'wait';
const getStepStatus = (order?: ParkingOrderDetail): { out: TStatus; end: TStatus } => {
  if (order?.isEnded || order?.canceled) return { out: 'finish', end: 'finish' };
  if (order?.carOut) return { out: 'process', end: 'wait' };
  return { out: 'wait', end: 'wait' };
};
const { Step } = Steps;

const handleLongText = (str: string = '') => {
  return str.slice(0, 20) + (str.length > 20 ? '...' : '');
};

// const getCanRefundAmount = (num1 = 0, num2 = 0) => Math.max(num1 - num2, 0);
export default () => {
  const history = useHistory<string>();
  const { initialState } = useModel('@@initialState');
  const [loading, setLoading] = useState<boolean>(false);
  const [currOrder, setCurrOrder] = useState<ParkingOrderDetail>();
  const [orderNo] = useState(history.location.state || '');
  const currUser = initialState?.currentUser;
  const auths = currUser?.auth ? new Set(currUser.auth.parkingOrder || []) : new Set();
  const ifModify = auths.has(Auths.MODIFY);
  const refreshDetail = () => {
    if (orderNo) {
      setLoading(true);
      getParkingOrder(orderNo).then((res) => {
        if (res?.success) {
          setCurrOrder(res.data);
          return;
        } else {
          setCurrOrder(undefined);
          message.error({ key: 'order_detail', content: res?.message || '获取失败' });
          return;
        }
      });
      setLoading(false);
    }
  };
  useEffect(() => {
    if (orderNo && orderNo.length > 0) {
      setLoading(true);
      getParkingOrder(orderNo).then((res) => {
        if (res?.success) {
          setCurrOrder(res.data);
          setLoading(false);
          return;
        } else {
          message.error({ key: 'order_detail', content: res?.message || '获取失败' });
          setLoading(false);
          return;
        }
      });
    }
  }, [orderNo]);

  return (
    <PageHeaderWrapper
      header={{
        breadcrumb: {},
        title: '',
      }}
    >
      {currOrder ? (
        <ProCard
          direction="column"
          bodyStyle={{
            padding: '10px 20px',
          }}
          className={styles.detail}
        >
          <ProCard
            gutter={1}
            title={
              <div>
                <ContainerOutlined
                  style={{
                    color: '#888',
                  }}
                />
                <span style={{ margin: '0 12px 0 8px' }}>
                  订单编号：{currOrder?.orderNo || orderNo}
                </span>
                <EnhancedTag
                  payStatus={currOrder?.payStatus}
                  status={currOrder?.status}
                  isEnded={currOrder?.isEnded}
                  carOut={currOrder?.carOut}
                  canceled={currOrder?.canceled}
                />
              </div>
            }
            extra={
              <a style={{ fontWeight: 'bold', fontSize: '16px' }} onClick={() => history.goBack()}>
                &lt; 返回
              </a>
            }
          >
            <ProCard
              colSpan={5}
              title="停车路段"
              layout="center"
              bodyStyle={{
                padding: 0,
                position: 'relative',
              }}
              style={{
                backgroundColor: '#eee',
                height: '130px',
              }}
            >
              <span className={styles.cardtext}>
                <Tooltip title={currOrder?.parkingLotName || ''}>
                  {handleLongText(currOrder?.parkingLotName) || ''}
                </Tooltip>
              </span>
            </ProCard>
            <ProCard
              colSpan={3}
              title="泊位编号"
              layout="center"
              bodyStyle={{
                padding: 0,
                position: 'relative',
              }}
              style={{
                backgroundColor: '#eee',
                height: '130px',
              }}
            >
              <span className={styles.cardtext}>{currOrder?.spotId || '暂无数据'}</span>
              <span className={styles.sensorInfo}>
                地磁编号: {currOrder?.sensorSn || '暂无数据'}
              </span>
            </ProCard>
            <ProCard
              colSpan={4}
              layout="center"
              bodyStyle={{
                padding: 0,
              }}
              title={
                <>
                  车牌号码
                  {currOrder && !currOrder.canceled && ifModify && (
                    <ChangePlate
                      reload={() => {
                        refreshDetail();
                      }}
                      orderNo={currOrder.orderNo}
                      plateNumber={currOrder.plateNumber || ''}
                      plateColor={currOrder.plateColor}
                      vehicleType={currOrder.vehicleType}
                    />
                  )}
                </>
              }
              style={{
                backgroundColor: '#eee',
                height: '130px',
              }}
            >
              <span className={styles.cardtext}>{currOrder?.plateNumber || '暂无数据'}</span>
              {/* <EditOutlined twoToneColor="#5895d0" /> */}
            </ProCard>
            <ProCard
              colSpan={6}
              layout="center"
              title={
                <>
                  停车时长
                  {currOrder &&
                    !currOrder.isEnded &&
                    !currOrder.canceled &&
                    currOrder.carOut &&
                    ifModify && (
                      <ChangeTime
                        currOrder={currOrder}
                        reload={() => {
                          refreshDetail();
                        }}
                      />
                    )}
                </>
              }
              bodyStyle={{
                padding: 0,
              }}
              style={{
                backgroundColor: '#eee',
                height: '130px',
              }}
            >
              <span className={styles.cardtext}>
                {diffTimes(currOrder?.outTime || new Date(), currOrder?.inTime)}
              </span>
            </ProCard>
            <ProCard
              colSpan={3}
              layout="center"
              title="应付金额(元)"
              bodyStyle={{
                padding: 0,
              }}
              style={{
                backgroundColor: '#eee',
                height: '130px',
              }}
            >
              <span className={styles.cardtext}>
                {numFormat((currOrder?.payableAmount || 0) / 100)}
              </span>
            </ProCard>
            <ProCard
              colSpan={3}
              layout="center"
              title="实付金额(元)"
              bodyStyle={{
                padding: 0,
              }}
              style={{
                backgroundColor: '#eee',
                height: '130px',
              }}
            >
              <span className={styles.cardtext}>
                {numFormat((currOrder?.actualAmount || 0) / 100)}
              </span>
            </ProCard>
          </ProCard>
          {currOrder?.isMember && (
            <span
              style={{
                paddingLeft: '28px',
                color: '#999',
              }}
            >
              * 会员卡车辆，免去费用
            </span>
          )}
          <ProCard ghost>
            {currOrder && !currOrder?.isMember && (
              <ProCard
                colSpan={12}
                bodyStyle={{
                  paddingTop: '5px',
                  paddingBottom: '5px',
                }}
                title={
                  <>
                    <BarsOutlined
                      style={{
                        color: '#888',
                      }}
                    />
                    <span style={{ margin: '0 12px 0 8px' }}>收费规则</span>
                  </>
                }
              >
                {/* <RulesDetail chargeRule={currOrder.chargeRule} flag /> */}
                {/* <ChargeRule chargeRule={currOrder.chargeRule} carType={currOrder.vehicleType} /> */}
                {currOrder.isImport ? (
                  <div>导入订单，无对应收费规则</div>
                ) : (
                  <ChargeRule chargeRule={currOrder.chargeRule} carType={currOrder.vehicleType} />
                )}
              </ProCard>
            )}
            <ProCard
              title={
                <>
                  <PictureOutlined
                    style={{
                      color: '#888',
                    }}
                  />
                  <span style={{ margin: '0 12px 0 8px' }}>停车图片</span>
                </>
              }
              bodyStyle={{
                paddingTop: '5px',
                paddingBottom: '5px',
              }}
            >
              {currOrder && currOrder?.imageArr?.length > 0 ? (
                <Image.PreviewGroup>
                  {currOrder?.imageArr?.map((item) => (
                    <Image width={180} height={200} src={item} key={item} />
                  ))}
                </Image.PreviewGroup>
              ) : (
                '暂无图片'
              )}
            </ProCard>
          </ProCard>

          <ProCard
            title={
              <>
                <FieldTimeOutlined
                  style={{
                    color: '#888',
                  }}
                />
                <span style={{ margin: '0 12px 0 8px' }}>交易过程</span>
              </>
            }
            bodyStyle={{
              paddingTop: '5px',
              paddingBottom: '5px',
            }}
          >
            <div>
              <Steps style={{ paddingTop: '50px', width: '100%' }} labelPlacement="vertical">
                <Step
                  status="finish"
                  title="车辆驶入"
                  icon={<EnhancedTip icon={<CarOutlined />} text={timeRender(currOrder?.inTime)} />}
                  description={handleInOutType(currOrder?.inType)}
                />
                <Step
                  status="finish"
                  title={currOrder?.ticketPrintTime ? '打印小票' : '订单生成'}
                  icon={
                    <EnhancedTip
                      icon={<ContainerOutlined />}
                      text={timeRender(currOrder?.ticketPrintTime || currOrder?.createTime)}
                    />
                  }
                  description={currOrder?.ticketPrintTime ? '人工打印' : '系统生成'}
                />
                {!currOrder?.carOut && (
                  <Step
                    status={'process'}
                    title="停车中"
                    icon={<EnhancedTip icon={<LoadingOutlined />} text={timeRender(Date.now())} />}
                  />
                )}
                <Step
                  status={getStepStatus(currOrder).out}
                  title="车辆驶出"
                  icon={
                    <EnhancedTip
                      icon={<CheckCircleOutlined />}
                      text={timeRender(currOrder?.outTime)}
                    />
                  }
                  description={currOrder?.carOut && handleInOutType(currOrder?.outType)}
                />
                <Step
                  status={getStepStatus(currOrder).end}
                  title="订单结束"
                  icon={
                    <EnhancedTip
                      icon={<SmileOutlined />}
                      text={timeRender(currOrder?.orderEndedTime || currOrder?.cancelTime)}
                    />
                  }
                  description={((order) => {
                    if (order.canceled) return '已作废';
                    return (
                      currOrder?.isEnded &&
                      (currOrder?.endType === 'manual' ? '人工审核' : '系统结算')
                    );
                  })(currOrder)}
                />
              </Steps>
            </div>
          </ProCard>
          {currOrder && currOrder.plateChangeLogs?.length > 0 && (
            <ProCard
              title={
                <>
                  <ReconciliationOutlined style={{ color: '#888' }} />
                  <span style={{ margin: '0 12px 0 8px' }}>车牌变更记录</span>
                </>
              }
            >
              <ChangeLogList logList={currOrder.plateChangeLogs} />
            </ProCard>
          )}
          {currOrder && currOrder.timeChangeLogs?.length > 0 && (
            <ProCard
              title={
                <>
                  <ReconciliationOutlined style={{ color: '#888' }} />
                  <span style={{ margin: '0 12px 0 8px' }}>时间变更记录</span>
                </>
              }
            >
              <ChangeTimeList changeList={currOrder.timeChangeLogs} />
            </ProCard>
          )}
          {currOrder && (
            <ProCard
              title={
                <>
                  <PayCircleOutlined
                    style={{
                      color: '#888',
                    }}
                  />
                  <span style={{ margin: '0 12px 0 8px' }}>支付记录</span>
                </>
              }
              bodyStyle={{
                paddingTop: '5px',
                paddingBottom: '5px',
              }}
            >
              <PaymentRecord
                orderNo={orderNo}
                payStatus={currOrder.payStatus}
                canRefundAmount={Math.max(currOrder?.actualAmount, 0)}
                carOut={currOrder?.carOut}
                records={currOrder?.paymentRecords}
                refundRecords={currOrder?.refundRecords || []}
                refresh={() => refreshDetail()}
              />
            </ProCard>
          )}
          {/* <div style={{ width: '100%', textAlign: 'center' }}> */}
          {currOrder?.carOut && !currOrder.canceled && ifModify && currOrder?.actualAmount <= 0 && (
            <CancelOrder
              orderNo={currOrder.orderNo}
              reload={() => {
                refreshDetail();
              }}
            />
          )}
        </ProCard>
      ) : (
        <LoadInfo
          loading={loading}
          action={() => {
            history.goBack();
          }}
          actionText={<>&lt; 返回订单列表</>}
        />
      )}
    </PageHeaderWrapper>
  );
};
